let modelDomain = "4.0Ultra"; // V1.1-V3.5动态获取，高于以上版本手动指定
//APPID，APISecret，APIKey在https://console.xfyun.cn/services/cbm这里获取
const ID = "a6241e4f";
const SECRET = "YjQ0NjZkODEyZGRlOTVhMTVlNTMzODlk";
const KEY = "93bfcdafcdc741ce29e0fb1627c0dfd9";

var total_res = "";

function getWebsocketUrl() {
  return new Promise((resolve, reject) => {
    var apiKey = KEY;
    var apiSecret = SECRET;

    var url = "wss://spark-api.xf-yun.com/v4.0/chat";

    var host = location.host;
    var date = new Date().toGMTString();
    var algorithm = "hmac-sha256";
    var headers = "host date request-line";
    var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${"/v4.0/chat"} HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    resolve(url);
  });
}

class TTSRecorder {
  constructor({ appId = ID } = {}) {
    this.appId = appId;
    this.status = "init";
  }

  // 修改状态
  setStatus(status) {
    this.onWillStatusChange && this.onWillStatusChange(this.status, status);
    this.status = status;
  }

  // 连接websocket
  connectWebSocket() {
    this.setStatus("ttsing");
    return getWebsocketUrl().then((url) => {
      let ttsWS;
      if ("WebSocket" in window) {
        ttsWS = new WebSocket(url);
      } else if ("MozWebSocket" in window) {
        ttsWS = new MozWebSocket(url);
      } else {
        alert("浏览器不支持WebSocket");
        return;
      }
      this.ttsWS = ttsWS;
      ttsWS.onopen = (e) => {
        this.webSocketSend();
      };
      ttsWS.onmessage = (e) => {
        this.result(e.data);
      };
      ttsWS.onerror = (e) => {
        clearTimeout(this.playTimeout);
        this.setStatus("error");
        alert("WebSocket报错，请f12查看详情");
        console.error(`详情查看：${encodeURI(url.replace("wss:", "https:"))}`);
      };
      ttsWS.onclose = (e) => {
        console.log(e);
        // 添加消息
        console.log(total_res);
        console.log(handleFunctionCall(total_res));
        const { toods, reply } = handleFunctionCall(total_res); // 解构赋值，获取 toods 和 reply 字段的值
        if (toods && toods.length > 0) {
          // 调用函数
          toods.forEach((todo) => {
            const { function: func, args } = todo; // 解构赋值，获取 function 和 args 字段的值
            if (typeof win[func] === "function") {
              // 判断函数是否存在
              win[func](...args); // 调用函数并传入参数
            }
          });
        }
        // 处理消息
        addMessage(reply, "assistant");
      };
    });
  }

  // websocket发送数据
  webSocketSend() {
    console.log(modelDomain);
    var params = {
      header: {
        app_id: this.appId,
        uid: "fd3f47e4-d",
      },
      parameter: {
        chat: {
          domain: modelDomain,
          temperature: 0.5,
          max_tokens: 1024,
        },
      },
      payload: {
        message: {
          text: msg,
        },
      },
    };
    console.log(JSON.stringify(params));
    this.ttsWS.send(JSON.stringify(params));
  }

  start() {
    total_res = ""; // 请空回答历史
    this.connectWebSocket();
  }

  // websocket接收数据的处理
  result(resultData) {
    let jsonData = JSON.parse(resultData);
    total_res = total_res + jsonData.payload.choices.text[0].content;
    // 提问失败
    if (jsonData.header.code !== 0) {
      alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`);
      console.error(`${jsonData.header.code}:${jsonData.header.message}`);
      return;
    }
    if (jsonData.header.code === 0 && jsonData.header.status === 2) {
      this.ttsWS.close();

      bigModel.setStatus("init");
    }
  }
}

let bigModel = new TTSRecorder();
bigModel.onWillStatusChange = function (oldStatus, status) {};
